package com.yangsir.mysite.controller;

import com.yangsir.mysite.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * java 8
 */
@CrossOrigin
@RestController
@RequestMapping("common")
public class CommonController {
    @Value("${mysite.path}")
    String filePath;

    /**
     * 文件上传到后端
     *
     * @param file
     * @return
     */
    @PostMapping("upload")
    public R<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //防止文件重名
        String fileName = UUID.randomUUID().toString() + suffix;
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(filePath + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName, "文件上传成功");
    }

    /**
     * 文件下载
     *
     * @param name
     * @param response
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response) {
        if (name == null) {
            return;
        }
        try {
            String[] split = name.split("\\.");
            response.setContentType("image/" + split[split.length - 1]);
            FileInputStream file = new FileInputStream(new File(filePath + name));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = file.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            file.close();
        } catch (IOException e) {
            System.out.println("文件下载失败:" + name);
            throw new RuntimeException(e);
        }
    }
}
